<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>实现拖放、碰撞检测、交互性操作等功能</title>
  <script src="/konva.min.js"></script>
  <style>
    body {
      margin: 0;
      padding: 0;
      overflow: hidden;
      background-color: #f0f0f0;
    }
  </style>
</head>

<body>
  <h3>
    Group 获取指定位置下的图层上的形状对象
  </h3>
  <hr>
  <div id="container"></div>


  <script>
    // 首先我们需要一个舞台（stage）和一层(layer)
    var stage = new Konva.Stage({
      container: 'container',   // 容器的 ID
      width: window.innerWidth,
      height: window.innerHeight
    })

    var layer = new Konva.Layer()
    stage.add(layer)

    // 创建两个矩形
    var rect1 = new Konva.Rect({
      x: 50,
      y: 70,
      width: 400,
      name: 'rect1',
      height: 400,
      fill: 'red',
      draggable: true
    })

    var rect2 = new Konva.Rect({
      x: 150,
      y: 90,
      name: 'rect2',
      width: 100,
      height: 50,
      fill: 'green',
      draggable: true
    })

    layer.add(rect1)
    layer.add(rect2)
    layer.draw()

    // 添加拖拽移动的事件监听
    rect1.on('dragmove', function () {
      var pos = stage.getPointerPosition()
      var intersection = stage.getIntersection(pos)

      console.log('%c [  ]-75', 'font-size:13px; background:pink; color:#bf2c9f;', intersection.attrs)
    })

    rect2.on('dragmove', function () {
      checkIntersection()
    })

    function checkIntersection () {

      var pos = stage.getPointerPosition()
      var intersection = stage.getIntersection(pos)

      if (intersection) {
        console.log('当前鼠标指针下的形状是：', intersection.shape)
      }
    }

    // 你也可以使用 mousemove 事件来检测鼠标下方的对象
    stage.on('mousemove', function () {
      // var intersect = stage.getIntersection(stage.getPointerPosition())
      // if (intersect) {
      //   console.log('鼠标下方的对象：', intersect.shape)
      // }
    });

  </script>
</body>

</html>